# app/api/v1/items.py
import asyncio
from fastapi import APIRouter, Depends, HTTPException
from core.security import get_current_user, get_current_user_m
from core.logger import log
from services.wx_friends_service import create_wx_friends
from services.wx_user_service import get_wx_user, create_wx_user, update_wx_usr_status, update_monitor_status, \
    update_wx_user_id
from utils.result import Result
from utils.wechat_pad_tools import WeChatPadClient

router = APIRouter()


@router.get("/wx_users")
async def get_wx_list(user = Depends(get_current_user_m), is_rag: bool = None):
    users = await get_wx_user(user, is_rag)
    if users:
        return Result.success(data=users, msg="查询成功")
    else:
        return Result.fail(code=400, msg="未找到用户")
@router.post("/wx_users")
async def create_wx_user_api(user = Depends(get_current_user)):
    result = await create_wx_user(user)
    if not result:
        raise HTTPException(status_code=400, detail="用户创建失败")
    return Result.success(msg="创建成功")

@router.post("/wx_users/sync_friends")
async def sync_friends(data: dict):
    result = await create_wx_friends(data["auth_key"], data["device_id"])
    return result.dict()

@router.post("/wx_users/assign")
async def assign_wx_user(data: dict):
    result = await update_wx_user_id(data["device_id"], data["user_id"])
    if not result:
        return Result.fail(msg="绑定失败")
    return Result.success(msg="绑定成功")


@router.get("/GetLoginQrCodeNew")
async def get_login_qr_code():
    wx_client = WeChatPadClient()
    token_key_dict = wx_client.get_unuse_devices()
    if not token_key_dict:
        authKey = wx_client.create_device()
        if not authKey:
            return Result.fail(code=400, msg="创建设备失败").dict()
        res = wx_client.post_login_qr_code(key=authKey)
    else:
        res= wx_client.post_login_qr_code(key=token_key_dict["authKey"])
    try:
        data = res.json()["Data"]
        data["Key"] = token_key_dict["authKey"]
    except:
        return Result.fail(code=400, msg="获取二维码失败").dict()
    return Result.success(data=data, msg="查询成功").dict()


@router.get("/GetLoginQrCodeNew/status/{auth_key}")
async def get_login_status(auth_key: str):
    wx_client = WeChatPadClient()
    res_json = wx_client.check_login_status(auth_key=auth_key).json()
    if res_json["Code"] == 200:
        state = res_json["Data"]["state"]
        return Result.success(data={"state": state}, msg="监测成功").dict()
    else:
        return Result.fail(code=400, msg="检测状态失败").dict()


@router.get("/wx_users/{auth_key}/wake")
async def wake_up_wx(auth_key: str):

    wx_client = WeChatPadClient()
    try:
        res = wx_client.wake_up_wx(auth_key)
        res_json = res.json()
        if res_json["Code"] != 200:
            return Result.fail(code=400, msg="唤醒登录失败").dict()
        return Result.success(data=res_json, msg="唤醒登录成功").dict()
    except Exception as e:
        log.error("唤醒登录失败: %s", e)
        return Result.fail(code=400, msg="唤醒登录失败").dict()

@router.get("/wx_users/{auth_key}/refresh")
async def refresh_wx_status(auth_key: str):
    """刷新微信用户状态 首先发送接口像服务器进行请求数据，获取当前用户的在线状态"""
    wx_client = WeChatPadClient()
    try:
        if auth_key=="123456":
            return Result.success(data=True).dict()
        res = wx_client.get_user_status(key=auth_key)
        log.info(res.json())
        if res.json()["Code"] != 200:
            loginState = 0
        else:
            loginState = res.json()["Data"]["loginState"]

        updated = await update_wx_usr_status(auth_key=auth_key,status=loginState)
        return Result.success(data=res.json(), msg="刷新成功").dict()
    except Exception as e:
        log.error(f"刷新失败:{e}", )
        return Result.fail(code=400, msg="刷新失败").dict()






